import { NzModalRef } from 'ng-zorro-antd/modal';
import { Component, Input, OnInit } from '@angular/core';
import { ExceptionHandler } from 'src/app/handler/exception.handler';
import { OrganizationTree, AccountRoles } from 'src/app/models';
import { OrganizationService } from 'src/app/services/organization.service';
import { RoleService } from 'src/app/services/role.service';

@Component({
  selector: 'zepride-edit-role-user-modal',
  templateUrl: './edit-role-user-modal.component.html',
  styleUrls: ['./edit-role-user-modal.component.less']
})
export class EditRoleUserModalComponent implements OnInit {
  @Input() departmentNodes: OrganizationTree[] = [];
  @Input() roleId: string;
  employeeNodes: OrganizationTree[] = [];


  constructor(
    private modal: NzModalRef,
    private orgSvr: OrganizationService,
    private roleSvr: RoleService
  ) { }

  async ngOnInit() {
    await this.getEmployeeList();
    this.formatData();
  }

  async getEmployeeList() {
    try {
      this.employeeNodes = await this.orgSvr.getOrganizationTrees({
        objectName: 'User'
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  formatData() {
    for (let department of this.departmentNodes) {
      department.employeeList = this.employeeNodes.filter(x => x.parentId == department.id);
    }
  }

  async ok() {
    const selectedEmployies = this.employeeNodes.filter(x => (<any>x).selected);
    if (selectedEmployies.length == 0) {
      this.modal.close('ok');
      return;
    }
    let accountRoleList: AccountRoles[] = selectedEmployies.map(employeeNode => {
      return {
        accountId: employeeNode.object.accountId,
        roleId: this.roleId
      };
    });

    await this.roleSvr.createAccountRoles(accountRoleList);
    this.modal.close('ok');
  }
  cancel() {
    this.modal.close();
  }

}
